import { Modal, Form, Input, Button, Space, message, Radio, Select } from 'antd'
import http from '../api/http'
import type { IEvaluate } from '../types/evaluate'
import type { FormInstance } from 'antd'
import { useEffect, useState } from 'react'
import dayjs from 'dayjs'

// 组合分类选项类型
interface GroupType {
  id: string
  name: string
}

interface Props {
  isModalOpen: boolean
  handleCancel: () => void
  onSuccess: () => void
}

const Add: React.FC<Props> = ({ isModalOpen, handleCancel, onSuccess }) => {
  const [form] = Form.useForm<FormInstance<any>>() // 使用通用类型适配评估表
  // 组合分类选项（可根据实际需求从接口获取）
  const [groups, setGroups] = useState<GroupType[]>([
    { id: '肥胖', name: '肥胖' },
    { id: '高血压', name: '高血压' },
    { id: '糖尿病', name: '糖尿病' },
    { id: '正常人群', name: '正常人群' }
  ])

  // 重置表单
  useEffect(() => {
    if (!isModalOpen) {
      form.resetFields()
    }
  }, [form, isModalOpen])

  // 提交表单
  const handleSubmit = () => {
    form.validateFields()
      .then(values => {
        // 构建评估建议表提交数据
        const submitData = {
          ...values,
          id: 0, // 新增数据ID为0
          createtime: dayjs(new Date()).format("YYYY-MM-DD HH:mm:ss"),
          updatetime: dayjs(new Date()).format("YYYY-MM-DD HH:mm:ss")
        }

        // 调用评估建议表添加接口
        http.post('evaluate', submitData)
          .then(() => {
            message.success('添加成功')
            handleCancel() // 关闭弹窗
            form.resetFields() // 重置表单
            onSuccess() // 通知父组件刷新列表
          })
          .catch(err => {
            console.error('添加失败:', err)
            message.error('添加失败，请重试')
          })
      })
      .catch(info => {
        console.log('表单验证失败:', info)
        message.warning('请完善必填字段')
      })
  }

  return (
    <Modal
      title="添加评估建议" // 修改标题
      open={isModalOpen}
      onCancel={handleCancel}
      centered
      footer={[
        <Button key="cancel" onClick={handleCancel}>
          取消
        </Button>,
        <Button key="submit" type="primary" onClick={handleSubmit}>
          确认添加
        </Button>
      ]}
      width={600}
    >
      <Form
        form={form}
        layout="vertical"
        initialValues={{ state: 0, disadvice: 0 }} // 默认启用状态
      >
        {/* 评估名称 */}
        <Form.Item
          name="name"
          label="评估名称"
          rules={[{ required: true, message: '请输入评估名称' }]}
        >
          <Input placeholder="请输入评估名称" />
        </Form.Item>

        {/* 评估结果 */}
        <Form.Item
          name="result"
          label="评估结果"
          rules={[{ required: true, message: '请输入评估结果' }]}
        >
          <Input placeholder="请输入评估结果（如：肥胖与超重）" />
        </Form.Item>

        {/* 建议内容 */}
        <Form.Item
          name="advice"
          label="建议内容"
          rules={[{ required: true, message: '请输入建议内容' }]}
        >
          <Input.TextArea rows={4} placeholder="请输入详细的评估建议内容" />
        </Form.Item>

        {/* 组合分类 */}
        <Form.Item
          name="grp"
          label="组合分类"
          rules={[{ required: true, message: '请选择组合分类' }]}
        >
          <Select placeholder="请选择组合分类" style={{ width: '100%' }}>
            {groups.map(group => (
              <Select.Option key={group.id} value={group.id}>
                {group.name}
              </Select.Option>
            ))}
          </Select>
        </Form.Item>

        {/* 状态设置 */}
        <Space style={{ width: '100%' }}>
          <Form.Item
            name="state"
            label="状态"
            rules={[{ required: true, message: '请选择状态' }]}
            style={{ flex: 1 }}
          >
            <Radio.Group>
              <Radio value={0}>启用</Radio>
              <Radio value={1}>禁用</Radio>
            </Radio.Group>
          </Form.Item>

          <Form.Item
            name="disadvice"
            label="建议状态"
            rules={[{ required: true, message: '请选择建议状态' }]}
            style={{ flex: 1 }}
          >
            <Radio.Group>
              <Radio value={0}>启用</Radio>
              <Radio value={1}>禁用</Radio>
            </Radio.Group>
          </Form.Item>
        </Space>

        {/* 备注 */}
        <Form.Item
          name="remark"
          label="备注"
        >
          <Input.TextArea rows={3} placeholder="请输入备注信息（可选）" />
        </Form.Item>
      </Form>
    </Modal>
  )
}

export { Add }